$(document).ready(function () {

  // 转换函数示例（根据实际换算比例）
  function convertToCt (kgValue) {
    return (parseFloat(kgValue) * 5000).toFixed(2) // 1 Kg = 5000 Ct
  }

  function convertToKg (ctValue) {
    return (parseFloat(ctValue) / 5000).toFixed(2)
  }

  function bindEvents () {

    // 容错解析函数
    function safeParseFloat (value) {
      const num = parseFloat(value)
      return isNaN(num) ? 0 : num
    }

    const $unitToggle = $('#unitToggle')
    const $qtyUnit = $('.qty-unit')

    const leftUnit = 'kg'
    const rightUnit = 'Ct'
    $qtyUnit.text($unitToggle.is(':checked') ? rightUnit : leftUnit)



    // $qtyUnit.text($(this).is(':checked') ? rightUnit : leftUnit)

    // 事件委托
    $('.pd-description-left').on(
      'change',
      '.pd-detail-operation input[type="checkbox"]',
      function () {
        const $container = $(this).closest('.pd-detail-operation') // 找到当前组件的容器
        const $qtyUnit = $container.find('.qty-unit')
        const $input = $container.find('#quantity')
        const $switchWrapper = $container.find('.pd-detail-switch')
        // 读取当前开关状态
        const leftUnit = $switchWrapper
          .find('.unit-label')
          .first()
          .text()
          .trim()
        const rightUnit = $switchWrapper
          .find('.unit-label')
          .last()
          .text()
          .trim()

        // $qtyUnit.text($(this).is(':checked') ? rightUnit : leftUnit)

        if ($(this).is(':checked')) {
          // 切换到右侧单位
          $qtyUnit.text(rightUnit)
          console.log($input.val());
          $input.val(convertToCt(safeParseFloat($input.val()))) // 转换值
        } else {
          // 切换回左侧单位
          $qtyUnit.text(leftUnit)
          $input.val(convertToKg(safeParseFloat($input.val()))) // 转换值
        }
      }
    )

    // 数字加事件
    $('.pd-description-left').on('click', '#increase', function () {
      const $container = $(this).closest('.pd-detail-operation')
      const $input = $container.find('#quantity')
      $input.val(safeParseFloat($input.val()) + 1)
    })
    // 数字减去事件
    $('.pd-description-left').on('click', '#decrease', function () {
      const $container = $(this).closest('.pd-detail-operation')
      const $input = $container.find('#quantity')
      $input.val(safeParseFloat($input.val()) - 1)
    })

    // 监听数字输入框的失焦事件(输入完成）
    $('.pd-description-left').on('blur', '#quantity', function () {
      let val = parseInt($(this).val(), 10) || 0; // 转换为整数，非数字时归零
      if (val < 0) {
        $(this).val(0)
      }
    })

    // 监听移除事件
    $('.pd-description-left').on('click', '#remove-inquiry', function () {
      const $container = $('.pd-description-left'); // 父级列表容器
      const $item = $(this).closest('.pd-detail-operation'); // 当前被删除的行
      // 移除当前行
      $item.remove();
      // 移除数据（根据 ID 删除）
      LocalStore.removeItem("inquiryList", item => item.id === $item.data('id'));

      // 如果 inquiryList 为空，则显示没有数据
      if (LocalStore.get("inquiryList").length === 0) {
        $container.append(notDataHtml);
      }
    })
  }

  bindEvents();

  // 只显示第一个 tab 的内容
  $(".dm-introduction-show-content section").hide().eq(0).show();
  // 点击 tab
  $(".dm-introduction-tabsList li").on("click", function () {
    let index = $(this).index();
    // 切换 tab 的选中状态
    $(this).addClass("active").siblings().removeClass("active");

    // 显示对应内容
    $(".dm-introduction-show-content section")
      .hide()
      .eq(index)
      .show();
  });


  // 产品数据列表
  const productsDataList = {
    total: 10,
    pageSize: 9,  // 每页显示多少条数据
    currentPage: 1,
    list: [
      {
        id: 9,
        img: '../../img/PC/GroupPro.png',
        title: 'CB4512 Monocrystalline Synthetic Diamond',
        desc: 'Monocrystalline Synthetic Diamond is complete, transparent in color, high in strength, good in thermalstability, and low in magnetism...',
      }, {
        id: 9,
        img: '../../img/PC/GroupPro.png',
        title: 'CB4512 Monocrystalline Synthetic Diamond',
        desc: 'Monocrystalline Synthetic Diamond is complete, transparent in color, high in strength, good in thermalstability, and low in magnetism...',
      },
      {
        id: 9,
        img: '../../img/PC/GroupPro.png',
        title: 'CB4512 Monocrystalline Synthetic Diamond',
        desc: 'Monocrystalline Synthetic Diamond is complete, transparent in color, high in strength, good in thermalstability, and low in magnetism...',
      }, {
        id: 9,
        img: '../../img/PC/GroupPro.png',
        title: 'CB4512 Monocrystalline Synthetic Diamond',
        desc: 'Monocrystalline Synthetic Diamond is complete, transparent in color, high in strength, good in thermalstability, and low in magnetism...',
      }
    ]
  }

  // 渲染 产品列表
  function renderProductsList (resData) {
    // 找到对应内容容器
    const $container = $(`.products-content-list`);
    if (resData.list && resData.list.length > 0) {

      resData.list.forEach((item, idx) => {
        const $item = $(`
             <div class="products-content-item">
          <div class="products-img">
           <img src="${item.img}" alt="">
          </div>
          <div class="products-title">
          <p>${item.title}</p>
          </div>
          <div class="products-desc">
                ${item.desc}
          </div>
          <div class="products-btn">
            <button type="button" class="addBag">
              Add to bag
            </button>
            <button type="button" class="inquiry">
              Inquiry
            </button>
          </div>
        </div>
          `)
        $container.append($item)
      })
      renderPagination(resData.currentPage, resData.total, $container)
    }
  }
  renderProductsList(productsDataList)


  // 渲染分页
  function renderPagination (currentPage, total, render) {
    // 整个分页容器
    let $pagination = $('<div class="page-products"></div>');
    // 左箭头
    let $left = $(`<div  class="pagination-left page-btn" ${currentPage === 1 ? 'style="opacity:0.3;pointer-events:none;"' : ''}>
     <svg width="8" height="12" viewBox="0 0 8 12" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path
              d="M0.988692 5.82543C0.998591 5.48788 1.13512 5.15789 1.39998 4.90844L6.05289 0.526369C6.43646 0.161393 7.04713 0.179302 7.40866 0.566128C7.77402 0.953066 7.75625 1.55911 7.36895 1.92014L3.15485 5.88895L7.12913 10.0979C7.4945 10.4848 7.47673 11.0909 7.08943 11.4519C6.70201 11.8168 6.09518 11.799 5.73366 11.4121L1.34554 6.76493C1.09575 6.50039 0.978794 6.16297 0.988692 5.82543Z"
              fill="#586168" />
          </svg>
  </div>`);

    // 页码容器
    let $numbers = $('<div class="page-numbers"></div>');

    // 首页始终显示
    if (currentPage > 2) {
      $numbers.append(`<button class="page-number" data-page="1">1</button>`);
      if (currentPage > 3) {
        $numbers.append(`<span class="page-number">...</span>`);
      }
    }


    if (currentPage >= total - 2) {
      // ✅ 当前页在最后 3 页时，显示最后三页
      for (let i = total - 2; i <= total; i++) {
        if (i >= 1) {
          $numbers.append(`<button data-page="${i}" class="page-number ${i === currentPage ? 'active' : ''}">${i}</button>`);
        }
      }
    } else {
      // ✅ 正常显示：当前页和它后面两页
      $numbers.append(`<button class="page-number active">${currentPage}</button>`);
      for (let i = currentPage + 1; i <= Math.min(total, currentPage + 2); i++) {
        $numbers.append(`<button class="page-number" data-page="${i}">${i}</button>`);
      }
      if (currentPage < total - 2) {
        if (currentPage < total - 3) {
          $numbers.append(`<span class="page-number">...</span>`);
        }
        $numbers.append(`<button class="page-number" data-page="${total}">${total}</button>`);
      }
    }

    // 右箭头
    let $right = $(`<div class="pagination-right page-btn" ${currentPage === total ? 'style="opacity:0.3;pointer-events:none;"' : ''}>
   <svg width="7" height="12" viewBox="0 0 7 12" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path
              d="M6.79155 5.92141C6.79155 6.2591 6.66475 6.59295 6.40731 6.85005L1.88486 11.3666C1.51215 11.7427 0.901216 11.7427 0.528507 11.3666C0.151956 10.9906 0.151956 10.3843 0.528507 10.012L4.62446 5.92141L0.528507 1.83077C0.151956 1.45471 0.151956 0.848408 0.528507 0.476183C0.905058 0.100121 1.51215 0.10012 1.88486 0.476183L6.40731 4.99277C6.66475 5.24987 6.79155 5.58372 6.79155 5.92141Z"
              fill="#586168" />
          </svg>
  </div>`);

    // 拼接
    $pagination.append($left).append($numbers).append($right);
    // ⚡插入到列表容器下面
    // $('.products-content-list').next('.page-products').remove(); // 删除旧的
    // $('.products-content-list').after($pagination);
    render.next('.page-products').remove(); // 删除旧的
    render.after($pagination);

    // ✅ 点击事件（事件委托，避免重复绑定）
    $pagination.off('click').on('click', '.page-number, .page-btn', function () {
      let targetPage = currentPage;

      if ($(this).hasClass('page-number')) {
        targetPage = parseInt($(this).data('page'));
      } else if ($(this).hasClass('pagination-left')) {
        targetPage = currentPage - 1;
      } else if ($(this).hasClass('pagination-right')) {
        targetPage = currentPage + 1;
      }

      if (targetPage !== currentPage && targetPage >= 1 && targetPage <= total) {
        console.log(targetPage, '_targetPage');
        // ⚡ 调用接口，重新渲染
        // loadTabData(tabName, targetPage);
      }
    })
  }

  // 定义映射关系
  const dropdownMap = {
    '#countryList': DropdownOptions.CountryListSelect || [],
    '#retailerList': DropdownOptions.RetailerOptions || [],
    '#diamondList': DropdownOptions.DiamondOptions || [],
    '#quantityList': DropdownOptions.QuantityOptions || []
  }
  // 渲染函数
  function renderOptions ($ul, options) {
    $ul.empty()
    options.forEach(opt => {
      $ul.append(`<li data-value="${opt.value}">${opt.label}</li>`)
    })
  }


  // 批量渲染
  Object.entries(dropdownMap).forEach(([selector, options]) => {
    renderOptions($(selector), options)
  })

  // 打开/关闭当前下拉（并关闭其它）
  $('.select-dropdown').on('click', function (e) {
    e.stopPropagation()
    $('.select-dropdown').not(this).removeClass('open')
    $(this).toggleClass('open')
  })
  $(document).on('click', () => $('.select-dropdown').removeClass('open'))
  $('.select-dropdown').click(function () {
    var dropdown = $(this)
    var ul = dropdown.children('ul')
    var p = dropdown.find('p')
    var input = dropdown.find('input')
    // 如果为二级下拉
    if (ul.find('ul li').length) {
      var li = ul.find('ul li')
    } else {
      // 一级
      var li = ul.find('li')
    }

    var arrows = dropdown.find('.select-arrows')
    if (ul.css('display') == 'none') {
      ul.slideDown('fast')
      arrows.css('transform', 'rotate(180deg)')
    } else {
      ul.slideUp('fast')
      arrows.css('transform', 'rotate(0)')
    }

    li.click(function () {
      var txt = $(this).text()
      var firstSelect = $(this).parent().prev().text()
      p.html(`${firstSelect} ${txt}`)
      input.val(`${firstSelect} ${txt}`)
      ul.slideUp('fast')
      arrows.css('transform', 'rotate(0)')
      // 如果选中的是 'Other'，则将 select-dropdown 的宽度设置为 50%
      if ($(this).parent().parent().hasClass('selfSelect')) {
        if (txt == 'Other') {
          dropdown.css('width', '50%')
          var itemssss = $(this).parent().parent().parent().find('.abcd')
          itemssss.css('width', '50%')
          // 展示 input
          dropdown.parent().find('.attribute_input').css('display', 'block')
        } else {
          dropdown.css('width', '100%')
          var itemssss = $(this).parent().parent().parent().find('.abcd')
          itemssss.css('width', '0')
          dropdown.parent().find('.attribute_input').css('display', 'none')
          dropdown.parent().find('.attribute_input').val('')
          dropdown.parent().find('.error-message').text('') // 移除错误信息
        }
      }
    })
    dropdown.mouseleave(function () {
      ul.slideUp('fast')
      arrows.css('transform', 'rotate(0)')
    })
  })

  // 点击其他地方关闭下拉
  $(document).click(function () {
    $('.select-dropdown').removeClass('open')
  })

  // 校验字段
  const validationRules = [
    {
      key: 'nameQuote',
      required: true,
      maxLength: 50,
      errorMessage: {
        required: 'Please enter your name',
        maxLength: 'The length cannot exceed 50'
      }
    },
    {
      key: 'companyName',
      required: true,
      maxLength: 50,
      errorMessage: {
        required: 'Please enter companyName',
      }
    },
    {
      key: 'diamondData',
      required: true,
      errorMessage: {
        required: 'Please select Diamond',
      }
    },
    {
      key: 'footerQuantity',
      required: true,
      errorMessage: {
        required: 'Please select quantity',
      }
    },
    {
      key: 'checkbox',
      required: false
    },
    {
      key: 'email',
      required: true,
      maxLength: 30,
      regex: regEmail,
      errorMessage: {
        required: 'Please enter your email',
        maxLength: 'The length cannot exceed 30',
        regex: 'Please enter a valid email'
      }
    },
    {
      key: 'country',
      required: true,
      errorMessage: {
        required: 'Please Select your Country'
      }
    },
    {
      key: 'retailer',
      required: true,
      errorMessage: {
        required: 'Please Select your Retailer'
      }
    },
    {
      key: 'phone',
      required: true,
      regex: regPhone,
      errorMessage: {
        required: 'Please enter your Phone',
        regex: 'Please enter a valid phone number'
      }
    }
  ]

  // 校验函数
  function validateField (rule) {
    const $input = $(`#${rule.key}`)
    const $error = $input.siblings('.error-message')
    const value = $input.val().trim()
    // 必填校验
    if (rule.required && !value) {
      $error.text(rule.errorMessage.required).addClass('show')
      return false
    }

    // 最大长度校验
    if (rule?.maxLength && value.length > rule.maxLength) {
      $error.text(rule.errorMessage.maxLength).addClass('show')
      return false
    }

    // 正则校验
    if (rule?.regex && value && !rule?.regex.test(value)) {
      $error.text(rule.errorMessage.regex).addClass('show')
      return false
    }

    // 校验通过
    $error.removeClass('show')
    return true
  }

  function getFormValues () {
    let allValid = true
    const formValues = {}
    validationRules.forEach(rule => {
      const $el = $("input[name='" + rule.key + "']")

      let value = ''
      if ($el.length) {
        if ($el.attr('type') === 'hidden') {
          value = $el.val() || ''
        } else {
          value = ($el.val() || '').trim()
        }
      }
      formValues[rule.key] = value
      // 校验必填或有校验规则的字段
      if (rule.required || rule.regex) {
        if (!validateField(rule)) {
          allValid = false
        }
      }
    })
    return allValid ? formValues : null
  }

  // 根据文件名获取 SVG
  function getFileIcon (filename) {
    const ext = filename.split('.').pop().toLowerCase()
    for (let item of ENUM_FILE_TYPE) {
      if (Array.isArray(item.label)) {
        if (item.label.includes(ext)) return item.svgIcon
      } else if (item.label === ext) {
        return item.svgIcon
      }
    }
    // 默认图标
    return `./img/PC/doc_pc.png`
  }

  const $fileInput = $('#uploadInput')
  const $uploadBtn = $('#handleUploadFile')
  const $fileContent = $('.file-content')
  let uploadedFiles = [] // 存储已上传的文件
  // 点击按钮触发文件选择
  $uploadBtn.on('click', function () {
    $fileInput.click()
  })

  // 文件选择后处理
  $fileInput.on('change', function (e) {
    const files = e.target.files
    if (!files || files.length === 0) return
    // 将文件添加到缓存数组
    uploadedFiles = uploadedFiles.concat(Array.from(files))

    // 遍历文件
    Array.from(files).forEach(file => {
      // 上传成功后显示到页面（模拟）
      const svgIcon = getFileIcon(file.name)
      const formData = new FormData()
      formData.append('file', file)

      // 模拟上传，可替换成你的接口
      // 这里用 setTimeout 模拟异步上传
      setTimeout(() => {
        // 上传成功后显示到页面
        const fileHtml = `
      <div class="file-info">
        <div class="file-left-txt">
            <img src="${svgIcon}" alt="">
          <div class="file-name">${file.name}</div>
        </div>
        <img style="width:2rem;height:2rem;" src="../../img/PC/scusser_pc.png" alt="">
      </div>
    `
        $fileContent.append(fileHtml)
      }, 500)
    })

    // 重置 input，防止选择同一个文件不触发 change
    $fileInput.val('')
  })

  // 提交
  $('#handleSendBtn').click(function () {
    const formValues = getFormValues()
    if (!formValues) return
    console.log(uploadedFiles)
  })


  // 缩放图展示
  function infoZoomProduct () {
    const $mainImg = $('.pd-products-img-container img')
    const $thumbnails = $('.pd-description-bar ol li')

    // 默认显示第一个
    const $first = $thumbnails.eq(0)
    $first.addClass('selected')
    $mainImg.attr('src', $first.find('img').attr('src'))

    // 点击切换
    $thumbnails.on('click', function () {
      $(this).addClass('selected').siblings().removeClass('selected')
      const newSrc = $(this).find('img').attr('src')
      $mainImg.attr('src', newSrc)
    })
  }

  infoZoomProduct()
})
